#include "widget.h"
#include "ui_widget.h"
#include "readfile.h"

#include <QFileDialog>
#include <QMessageBox>
#include <QProgressDialog>
#include <QThread>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    ,thread(new QThread)
    ,readFile(new ReadFile)
{
    ui->setupUi(this);

    qDebug()<<"Widget threadId"<<QThread::currentThread();
    readFile->moveToThread(thread);

    connect(this,&Widget::readFileEmit,readFile,&ReadFile::readFile);

    progressDialog.setWindowTitle("任务进度");
    progressDialog.setWindowModality(Qt::WindowModal); // 设置为模态对话框
    // 调用reset函数，里面对定时器进行了stop，因此就不再会自动弹出
    progressDialog.reset();

    connect(readFile, &ReadFile::currentValue, &progressDialog, &QProgressDialog::setValue);
    thread->start();
}

Widget::~Widget()
{
    thread->quit();
    thread->wait();
    delete ui;
}



void Widget::on_threadBtn_clicked()
{
    emit readFileEmit(ui->filePath->text());
    // 千万不能使用下面的调用方式，这样只会让主线程执行文件的遍历
    // readFile->readFile(ui->filePath->text());
}


void Widget::on_selectBtn_clicked()
{
    QString path = QFileDialog::getOpenFileName(nullptr,"Open Text File",QDir::homePath(),"Text Files (*.txt);;All Files(*)");
    if(path.isEmpty())
    {
        QMessageBox::warning(this,"选择文件","选择的文件不能为空");
        return;
    }
    ui->filePath->setText(path);
}

